var Drag = function(option){
	option = option || {};
	var me = this;
	me.build = function(selector){
		me.nodeLists = document.querySelectorAll(selector);
		me.register();
	}
	
	me.register = function(){
		[].forEach.call(me.nodeLists, function(node) {
			node.addEventListener("mousedown", me.down(node), false);
			node.addEventListener("touchstart", me.down(node), false);
			node.addEventListener("mousemove", me.move, false);
			node.addEventListener("touchmove", me.move, false);
			node.addEventListener("mouseup", me.end, false);
			node.addEventListener("touchend", me.end, false);
		});
	}
	
	me.down = function(dom){
		return function(){
			me.flag = true;
			me.dom = dom;			
			
			var touch;
		 	if(event.touches) {
		 		touch = event.touches[0];
		 	} else {
		 		touch = event;
		 	}
		 	//当前dom的宽高
		 	var styles = getComputedStyle(me.dom);
		 	me.width = parseFloat(styles.width);
			me.height = parseFloat(styles.height);
		 	me.edge = option.edge || {
				left:0,
				right:0,
				top:0,
				bottom:0
			};
			me.edge.maxLeft = document.body.clientWidth - me.edge.right - me.width;//最右
			me.edge.maxTop = document.body.clientHeight  - me.edge.bottom - me.height;//最下		
			
		 	//当前dom为最大层
		 	var maxZIndex = getMaxZIndex(document.body,me.dom);
//		 	console.log("maxZIndex:" + maxZIndex);
		 	me.dom.style.zIndex = maxZIndex + 1;
		 	
		 	me.cur.x = touch.clientX;
		 	me.cur.y = touch.clientY;
		 	me.dx = me.dom.offsetLeft;
		 	me.dy = me.dom.offsetTop;	
		 	
		 	//阻止页面的滑动默认事件
			document.addEventListener("touchmove",me.preventFun, { passive: false });
		}
	}	
	
	me.move = function() {		
	 	if(!me.flag) {
	 		return;
	 	}
	 	
		var touch;
		if(event.touches) {
			touch = event.touches[0];
		} else {
			touch = event;
		}
		
		var nx = touch.clientX - me.cur.x;//移动了多少x
		var ny = touch.clientY - me.cur.y;//移动了多少y		
		var x = me.dx + nx;
		var y = me.dy + ny;
		//不能超过上下左右的边缘
		if(x < me.edge.left){
			x = me.edge.left;
		}else if(x > me.edge.maxLeft){
			x = me.edge.maxLeft;
		}
		
		if(y < me.edge.top){
			y = me.edge.top;
		}else if(y > me.edge.maxTop){
			y = me.edge.maxTop;
		}
		
		me.dom.style.left = x + "px";
		me.dom.style.top = y + "px";		
	}
	
	me.end = function(){
		me.flag = false;
   		document.removeEventListener('touchmove',me.preventFun,{ passive: false });
	}
	
	me.preventFun =  function() {
		event.preventDefault();
	}
	
	me.flag = false;
	me.cur = {x: 0,y: 0};
	var selector = option.selector;	
	if(selector){
		me.build(selector);
	}	
}
